package practice.hot100;

import java.util.ArrayList;
import java.util.List;

public class Solution93 {
    List<String> res = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        backtracking(0, s);
        return res;
    }

    List<Integer> list = new ArrayList<>();
    public void backtracking(int index, String s) {
        if (list.size() == 4) {
            if (index == s.length()) {
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < 4; i++) {
                    sb.append(list.get(i));
                    sb.append('.');
                }
                sb.deleteCharAt(sb.length() - 1);
                res.add(sb.toString());
            }
            return;
        }
        for (int i = index + 1; i <= s.length(); i++) {
            String tmp = s.substring(index, i);
            if (isValid(tmp)) {
                list.add(Integer.parseInt(tmp));
                backtracking(i, s);
                list.remove(list.size() - 1);
            } else break;
        }
    }

    public boolean isValid(String str) {
        if (str.length() > 1 && str.charAt(0) == '0') return false;
        int i = Integer.parseInt(str);
        return i <= 255;
    }
}
